var express = require('express')
var connection = require('../db/db_utill');

var router = express.Router()

// 用户关注
router.put('/user_attention', function (req, res) {
  //获取post数据
  const body = req.body
  const inserts = [body.user_id, body.attention_user_id]
  connection.query(`SELECT * FROM user_attention WHERE user_id=? and attention_user_id = ?`, inserts, function (error, results, fields) {
    if (error) {
      throw error;
    } else if (results.length) {
      //用户已经关注，则取消关注
      connection.query(`DELETE FROM user_attention WHERE user_id=? and attention_user_id = ?`, inserts, function (error, results, fields) {
        if (error) {
          throw error;
        } else {
          // 更新关注数据
          return res.json({
            status: 201,
            message: '取消关注成功！'
          })
        }
      });
    } else {
      // 用户没有关注
      connection.query(`INSERT INTO user_attention value(?,?)`, inserts, function (error, results, fields) {
        if (error) {
          throw error;
        } else {
          return res.json({
            status: 200,
            message: '关注成功！'
          })
        }
      });
    }
  });
})

//取消关注
router.post('/delete_attention', function (req, res) {
  //获取post数据
  const body = req.body
  const inserts = [body.user_id, body.attention_user_id]
  connection.query(`DELETE FROM user_attention WHERE user_id=? and attention_user_id = ?`, inserts, function (error, results, fields) {
    if (error) {
      throw error;
    } else {
      return res.json({
        status: 201,
        message: '取消关注成功！'
      })
    }
  });
})

//获取用户关注的用户
router.post('/user_attention', function (req, res) {
  //获取post发送用户id
  const id = req.body.userId
  connection.query(`SELECT * FROM user_info WHERE user_id in (select attention_user_id from user_attention where user_id = ?)`, [id], function (error, results, fields) {
    if (error) {
      throw error;
    } else if (results) {
      const string = JSON.stringify(results);
      const jsons = JSON.parse(string);
      res.json(jsons)
    }
  });
})

module.exports = router;
